package com.xxl.job.executor.core.config;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.mongodb.MongoClient;
import com.xxl.job.core.util.ListUtils;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 获取链接
 */
public class LinkConfig {

    //存储所有链接（JdbcTemplate 或者 MongoTemplate）
    private static Map<String, Object> linkMap = new HashMap<>();

    public static JdbcTemplate jdbcTemplate = null;
    static {
        if(jdbcTemplate == null) {
            try {
                String url = YmlConfigUtil.getConfigByKey("url");
                String username = YmlConfigUtil.getConfigByKey("username");
                String password = YmlConfigUtil.getConfigByKey("password");
                String driverClassName = YmlConfigUtil.getConfigByKey("driver-class-name");

                DriverManagerDataSource dataSource = new DriverManagerDataSource();
                dataSource.setDriverClassName(driverClassName);
                dataSource.setUrl(url);
                dataSource.setUsername(username);
                dataSource.setPassword(password);
                jdbcTemplate = new JdbcTemplate(dataSource);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }

        }
    }

    public static JdbcTemplate getJdbcTemplate(String belong, String name) {
        JdbcTemplate jdbcTemplate1 = (JdbcTemplate) linkMap.get(belong + "|" + name);
        if(jdbcTemplate1 == null) {
            String query = "select db_driver 'dbDriver',db_url 'dbUrl',db_user_name 'dbUserName',db_password 'dbPassword' from code_dbinfo where db_type = '1' and belong = '" + belong + "' and `name` = '" + name + "'";
            List<Map<String, Object>> list = jdbcTemplate.queryForList(query);
            if (ListUtils.isNotEmpty(list)) {
                Map<String, Object> map = list.get(0);
                System.out.println(JSON.toJSONString(map));
                DriverManagerDataSource dataSource = new DriverManagerDataSource();
                dataSource.setDriverClassName(map.get("dbDriver").toString());
                dataSource.setUrl(map.get("dbUrl").toString());
                dataSource.setUsername(map.get("dbUserName").toString());
                dataSource.setPassword(map.get("dbPassword").toString());
                jdbcTemplate1 = new JdbcTemplate(dataSource);
                linkMap.put(belong + "|" + name, jdbcTemplate1);
            }
        }
        return jdbcTemplate1;
    }

    public static MongoTemplate getMongoTemplate(String belong, String name) {
        MongoTemplate mongoTemplate = (MongoTemplate) linkMap.get(belong + "|" + name);
        if(mongoTemplate == null) {
            String query = "select db_url 'dbUrl',db_user_name 'dbUserName',db_password 'dbPassword',mongodb_port 'mongodbPort',mongodb_database 'mongodbDatabase' from code_dbinfo where db_type = '1' and belong = '" + belong + "' and `name` = '" + name + "'";
            List<Map<String, Object>> list = jdbcTemplate.queryForList(query);
            if (ListUtils.isNotEmpty(list)) {
                Map<String, Object> map = list.get(0);
                MongoDbFactory mongoDbFactory = new SimpleMongoDbFactory(new MongoClient(map.get("dbUrl").toString(), Integer.parseInt(map.get("mongodbPort").toString())), map.get("mongodbDatabase").toString());

                /*ServerAddress serverAddress = new ServerAddress(map.get("dbUrl").toString(), Integer.parseInt(map.get("mongodbPort").toString()));
                List<MongoCredential> credentialsList = new ArrayList<>();
                credentialsList.add(MongoCredential.createCredential(map.get("dbUserName").toString(), map.get("mongodbDatabase").toString(), map.get("dbPassword").toString().toCharArray()));
                mongoDbFactory = new SimpleMongoDbFactory(new MongoClient(serverAddress, credentialsList), map.get("mongodbDatabase").toString());*/
                mongoTemplate = new MongoTemplate(mongoDbFactory);
                linkMap.put(belong + "|" + name, mongoTemplate);
            }
        }
        return mongoTemplate;
    }
}
